#pragma once
#include "../common/util.hpp"
#include "../common/httplib.h"
#include "../common/Log.hpp"
#include "oj_model.hpp"
#include "oj_view.hpp"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <mutex>
#include <cassert>
#include <jsoncpp/json/json.h>
using namespace std;


// 提供服务的主机
class Machine
{
public:
    string ip;       //编译服务的ip
    int port;        //编译服务的port
    uint64_t load;   //编译服务的负载
    mutex *mtx;      // mutex禁止拷贝的，使用指针
public:
    Machine() : ip(""), port(0), load(0), mtx(nullptr)
    {
    }
    ~Machine()
    {
    }

public:
    // 提升主机负载
    void IncLoad()
    {
        if (mtx) 
            mtx->lock();
        ++load;
        if (mtx) 
            mtx->unlock();
    }

    // 减少主机负载
    void DecLoad()
    {
        if (mtx) 
            mtx->lock();
        --load;
        if (mtx) 
            mtx->unlock();
    }

    void ResetLoad()
    {
        if(mtx)
            mtx->lock();
        load = 0;
        if(mtx)
            mtx->unlock();
    }

    // 获取主机负载
    uint64_t Load()
    {
        uint64_t _load = 0;
        if (mtx) 
            mtx->lock();
        _load = load;
        if (mtx) 
            mtx->unlock();
        return _load;
    }
};

const string service_machine = "./conf/service_machine.conf";

// 负载均衡模块
class LoadBlance
{
private:
    // 每一台主机都有自己的下标，充当当前主机的id
    vector<Machine> machines;
    // 所有在线的主机id
    vector<int> online;
    // 所有离线的主机id
    vector<int> offline;
    // 保证LoadBlance它的数据安全
    mutex mtx;

public:
    LoadBlance()
    {
        assert(LoadConf(service_machine));
        lg(Info, "加载：%s 成功", service_machine.c_str());
    }
    ~LoadBlance()
    {
    }

public:
    bool LoadConf(const string &machine_conf)
    {
        ifstream in(machine_conf);
        if (!in.is_open())
        {
            lg(Fatal, "加载 %s 失败", machine_conf.c_str());
            return false;
        }
        string line;
        while (getline(in, line))
        {
            vector<string> tokens;
            StringUtil::SplitString(line, &tokens, ":");
            if (tokens.size() != 2)
            {
                lg(Info, "切分 %s 失败", line.c_str());
                continue;
            }
            Machine m;
            m.ip = tokens[0];
            m.port = atoi(tokens[1].c_str());
            m.load = 0;
            m.mtx = new mutex();

            online.push_back(machines.size());
            machines.push_back(m);
        }

        in.close();
        return true;
    }

    // 选择主机和机器
    bool SmartChoice(int *id, Machine **m)
    {
        // 1. 使用选择好的主机(更新该主机的负载)
        // 2. 需要可能离线该主机
        mtx.lock();
        // 负载均衡的算法: 轮询
        int online_num = online.size();
        if (online_num == 0)
        {
            mtx.unlock();
            lg(Fatal, "后端所有主机离线");
            return false;
        }
        // 通过遍历的方式，找到所有负载最小的机器
        *id = online[0];
        *m = &machines[online[0]];
        uint64_t min_load = machines[online[0]].Load();
        for (int i = 1; i < online_num; i++)
        {
            // 获取主机的负载，如果负载小就更新
            uint64_t curr_load = machines[online[i]].Load();
            if (min_load > curr_load)
            {
                min_load = curr_load;
                *id = online[i];
                *m = &machines[online[i]];
            }
        }
        mtx.unlock();
        return true;
    }

    // 离线某个主机
    void OfflineMachine(int which)
    {
        mtx.lock();
        for(auto iter = online.begin(); iter != online.end(); iter++)
        {
            if(*iter == which)
            {
                machines[which].ResetLoad();
                //要离线的主机已经找到啦
                online.erase(iter);
                offline.push_back(which);
                break;
            }
        }
        mtx.unlock();
    }

    void OnlineMachine()
    {
        mtx.lock();
        online.insert(online.end(), offline.begin(), offline.end());
        offline.erase(offline.begin(), offline.end());
        mtx.unlock();
        lg(Info, "所有主机已上线");
    }

    //for test
    void ShowMachines()
    {
        mtx.lock();
        cout << "当前在线主机列表: ";
        for(auto &id : online)
        {
            cout << id << " ";
        }
        cout << endl;
        cout << "当前离线主机列表: ";
        for(auto &id : offline)
        {
            cout << id << " ";
        }
        cout << endl;
        mtx.unlock();
    }
};

// 这是我们的核心业务逻辑的控制器
class Control
{
private:
    Model model_; //提供后台数据
    View view_;   //提供html渲染功能
    LoadBlance load_blance_; //核心负载均衡器
public:
    Control()
    {
    }
    ~Control()
    {
    }

public:
    void RecoveryMachine()
    {
        load_blance_.OnlineMachine();
    }
    //根据题目数据构建网页
    // html: 输出型参数
    bool AllQuestions(string *html)
    {
        bool ret = true;
        vector<struct Question> all;
        if (model_.GetAllQuestions(&all) && !all.empty())
        {
            sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2){
                return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
            });
            // 获取题目信息成功，将所有的题目数据构建成网页
            view_.AllExpandHtml(all, html);
        }
        else
        {
            *html = "获取题目失败, 形成题目列表失败";
            ret = false;
        }
        return ret;
    }
    bool Question(const string &number, string *html)
    {
        bool ret = true;
        struct Question q;
        if (model_.GetOneQuestion(number, &q))
        {
            // 获取指定题目信息成功，将所有的题目数据构建成网页
            view_.OneExpandHtml(q, html);
        }
        else
        {
            *html = "指定题目: " + number + " 不存在!";
            ret = false;
        }
        return ret;
    }
    // code: #include...
    // input: ""
    void Judge(const string &number, const string in_json, string *out_json)
    {   
        // 0. 根据题目编号，直接拿到对应的题目细节
        struct Question q;
        model_.GetOneQuestion(number, &q);

        // 1. in_json进行反序列化，得到题目的id，得到用户提交源代码，input
        Json::Reader reader;
        Json::Value in_value;
        reader.parse(in_json, in_value);
        string code = in_value["code"].asString();

        // 2. 重新拼接用户代码+测试用例代码，形成新的代码
        Json::Value compile_value;
        compile_value["input"] = in_value["input"].asString();
        compile_value["code"] = code + "\n" + q.tail;
        compile_value["cpu_limit"] = q.cpu_limit;
        compile_value["mem_limit"] = q.mem_limit;
        Json::FastWriter writer;
        string compile_string = writer.write(compile_value);
        cout << compile_string << endl;
        // 3. 选择负载最低的主机(差错处理)
        // 规则: 一直选择，直到主机可用，否则，就是全部挂掉
        while(true)
        {
            int id = 0;
            Machine *m = nullptr;
            if(!load_blance_.SmartChoice(&id, &m))
            {
                break;
            }

            // 4. 然后发起http请求，得到结果
            httplib::Client cli(m->ip, m->port);
            m->IncLoad();
            lg(Info, "选择主机成功, 主机ID: %d, 详情%s: %d, 当前主机负载为: %d", id, m->ip.c_str(), m->port, m->Load());
            if(auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
            {
                // 5. 将结果赋值给out_json
                if(res->status == 200)
                {
                    *out_json = res->body;
                    m->DecLoad();
                    lg(Info, "请求编译和运行服务成功");
                    break;
                }
                m->DecLoad();
            }
            else
            {
                //请求失败
                lg(Info, "当前请求的主机id: %d, 详情: %s : %d 可能离线", id, m->ip.c_str(), m->port);
                load_blance_.OfflineMachine(id);
                load_blance_.ShowMachines();
            }
        }
    }
};